package com.example.everying.utils;/*
 * 项目名称: everything
 * 文件名: WxCoreUtil
 * 作者: 张泽阳
 * 日期: 2025/5/14
 * 描述:
 */

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.example.everying.model.vo.user.ResolvePhoneVO;
import com.example.everying.model.vo.user.WxLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class WxCoreUtil {
    @Value("${wx.appid}")
    private String wxAppid;

    @Value("${wx.secret}")
    private String wxSecret;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 用预登录code向微信换取openId
     * @param code
     * @return
     */
    public ResolvePhoneVO getOpenId(String code){
        try{


            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
            url = String.format(url, wxAppid, wxSecret, code);
            System.out.println("向微信服务器请求OpenId：" + url);

            String str = restTemplate.getForObject(url, String.class);

            System.out.println("微信服务器返回内容：" + str);

            JSONObject obj = (JSONObject) JSON.parse(str);
            ResolvePhoneVO resolvePhoneVO = new ResolvePhoneVO();
            resolvePhoneVO.setOpenId(obj.getString("openid"));
            resolvePhoneVO.setSessionKey(obj.getString("session_key"));

            return resolvePhoneVO;
        }catch(Exception e){

            System.out.println("用code向微信服务器换取openid失败");
            e.printStackTrace();
            return null;
        }
    }
}
